package com.hxd.otc.module.order.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hxd.otc.R;
import com.hxd.otc.base.permission.PermissionActivity;
import com.hxd.otc.dialog.MultipleBlocksDialog;
import com.hxd.otc.dialog.SingBlocksDialog;
import com.hxd.otc.event.Event;
import com.hxd.otc.module.order.adapter.AdOrderDetailAlipayAdapter;
import com.hxd.otc.module.order.adapter.AdOrderDetailBankAdapter;
import com.hxd.otc.module.order.bean.AdOrderDetailBean;
import com.hxd.otc.module.order.contract.AdBuyOrderDetailContract;
import com.hxd.otc.module.order.fragment.AllOrderFragment;
import com.hxd.otc.module.order.presenter.AdBuyOrderDetailPresenter;
import com.hxd.otc.other.OnPermissionsResult;
import com.hxd.otc.utils.CommonUtil;
import com.hxd.otc.utils.CountDownUtils;
import com.hxd.otc.utils.DateUtil;
import com.hxd.otc.utils.GlideUtils;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.widget.BlocksToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 作  者 :  zjl
 * 时  间 :  2018/6/5 17:19
 * 描  述 :  ${广告商买入 订单详情页}
 */
public class AdBuyOrderDetailActivity extends PermissionActivity<AdBuyOrderDetailPresenter> implements AdBuyOrderDetailContract.View {

    @BindView(R.id.bt_right1)
    Button btRight1;

    @BindView(R.id.iv_head)
    CircleImageView ivHead;

    @BindView(R.id.tv_name)
    TextView tvName;

    @BindView(R.id.tb_cancled)
    TextView tbCancled;

    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;

    @BindView(R.id.tv_account)
    TextView tvAccount;

    @BindView(R.id.tv_pay_state)
    TextView tvPayState;

    @BindView(R.id.tv_time)
    TextView tvTime;

    @BindView(R.id.tv_red)
    TextView tvRed;

    @BindView(R.id.tv_price)
    TextView tvPrice;

    @BindView(R.id.tv_number)
    TextView tvNumber;


    @BindView(R.id.ll_pay_infom)
    LinearLayout llPayInfom;

    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;

    @BindView(R.id.v_line)
    View vBottomLine;

    @BindView(R.id.ll_agree)
    LinearLayout llAgree;

    @BindView(R.id.ll_all)
    LinearLayout llAll;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.rc_alipay)
    RecyclerView rcAlipay;

    @BindView(R.id.rc_bank)
    RecyclerView rcBank;
    /**
     * 订单 买入 状态
     */
    public static final int BUY_UNPAID = 0;//未付款
    public static final int BUY_PAYED = 1;//已付款
    public static final int BUY_REPRESENTATION = 2;//申诉中
    public static final int BUY_CANCLED = 3;//已取消
    public static final int BUY_FINISHED = 4;//已完成

    public static final int SALE_PAYED_REQUEST = 123;//申诉 requestCode

    public static final int CANCLE_CONFIRM_SUCCESS = 1;//同意取消订单操作成功
    public static final int REJECT_CONFIRM_SUCCESS = 5;//拒绝取消订单操作成功
    public static final int PAYIING_SUCCESS = 3;// 我已付款 操作成功

    AdOrderDetailBean orderBean;

    MultipleBlocksDialog callDailog;
    MultipleBlocksDialog payingDailog;

    SingBlocksDialog copyDialog;

    AdOrderDetailAlipayAdapter alipayAdapter;
    AdOrderDetailBankAdapter bankAdapter;

    Disposable mDisposable;

    String orderId;
    boolean isFrist = true;//
    int statue = -1;//记录订单状态是否改变
    boolean isRefreshRedMess;//刷新融云消息

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ad_buy_order_detail;
    }

    @Override
    protected void initView() {
        orderId = getIntent().getExtras().getString(AllOrderFragment.ORDER_ID);

        rcAlipay.setLayoutManager(new LinearLayoutManager(this));
        alipayAdapter = new AdOrderDetailAlipayAdapter(this);
        rcAlipay.setAdapter(alipayAdapter);
        rcAlipay.setNestedScrollingEnabled(false);


        rcBank.setLayoutManager(new LinearLayoutManager(this));
        bankAdapter = new AdOrderDetailBankAdapter();
        rcBank.setAdapter(bankAdapter);
        rcBank.setNestedScrollingEnabled(false);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doLoadData(orderId);
            }
        });

        alipayAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("alipayAddress", alipayAdapter.getData().get(position).alipayAddress);
                $startActivity(AlipayQRcodeActivity.class, bundle);
            }
        });
        bankAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                copyData(bankAdapter.getData().get(position).bankNo);
            }
        });

    }

    @Override
    protected void initData() {
        refreshLayout.autoRefresh(0, 10, 1);
    }

    @Override
    public void onSetData(AdOrderDetailBean bean) {
        orderBean = bean;
        if (isFrist) {
            statue = orderBean.orderVo.status;
            isFrist = false;
            if (orderBean.orderVo.status == 0 || orderBean.orderVo.status == 1 || orderBean.orderVo.status == 2)
                getRongUnreadCount();
        }
        refreshData();

        if (bean.payInfoVo.alipayInfoPos != null && bean.payInfoVo.alipayInfoPos.size() > 0 && bean.payInfoVo.alipayInfoPos.get(0) != null) {
            if (bean.payInfoVo.alipayInfoPos.size() > 5) {
                bean.payInfoVo.alipayInfoPos = bean.payInfoVo.alipayInfoPos.subList(0, 1);
            }
            alipayAdapter.setNewData(bean.payInfoVo.alipayInfoPos);
        }

        if (bean.payInfoVo.bankInfoPos != null && bean.payInfoVo.bankInfoPos.size() > 0 && bean.payInfoVo.bankInfoPos.get(0) != null) {
            if (bean.payInfoVo.bankInfoPos.size() > 5) {
                bean.payInfoVo.bankInfoPos = bean.payInfoVo.bankInfoPos.subList(0, 5);
            }
            bankAdapter.setNewData(bean.payInfoVo.bankInfoPos);
        }
    }

    @Override
    public void refreshView(int type) {
        setResult(RESULT_OK);
        switch (type) {
            case CANCLE_CONFIRM_SUCCESS:
                mPresenter.doLoadData(orderId);
                break;
            case REJECT_CONFIRM_SUCCESS:
                showToast(getString(R.string.reject_order_succed));
                llAgree.setVisibility(View.GONE);
                mPresenter.doLoadData(orderId);
                break;
            case PAYIING_SUCCESS:
                showToast(getString(R.string.pay_succed));
                mPresenter.doLoadData(orderId);
                break;
        }
    }

    @Override
    public void onHideLoading() {
        super.onHideLoading();
        refreshLayout.finishRefresh();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected AdBuyOrderDetailPresenter createPresenter() {
        return new AdBuyOrderDetailPresenter(this);
    }

    private void refreshData() {
        llAll.setVisibility(View.VISIBLE);
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        tvName.setText(orderBean.buyVo.nickName);
        GlideUtils.loadHeadImageView(this, orderBean.buyVo.avatar, ivHead, R.mipmap.order_head_portrait_img, R.mipmap.order_head_portrait_img);
        tvOrderNumber.setText(orderBean.orderVo.orderNo);
        tvAccount.setText(getString(R.string.deal_account, StringUtil.format2Number(orderBean.orderVo.money), orderBean.orderVo.legalCurrency));

        String[] split = orderBean.orderVo.transactionPair.split("/");
        if (split.length > 1) {
            tvNumber.setText(getResources().getString(R.string.number_detail, StringUtil.format2Number(orderBean.orderVo.quantity), split[0]));
            tvPrice.setText(getResources().getString(R.string.price_detail,
                    StringUtil.format2Number(orderBean.orderVo.unitPrice), orderBean.orderVo.legalCurrency + "/" + split[0]));
        }
        switch (orderBean.orderVo.status) {
            case BUY_UNPAID:
                llBottom.setVisibility(View.VISIBLE);
                vBottomLine.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFC807B));
                tvPayState.setText(getResources().getString(R.string.order_un_pay));

                btRight1.setVisibility(View.VISIBLE);
                btRight1.setText(getString(R.string.payed));
                btRight1.setBackgroundColor(getResources().getColor(R.color.color_FFFF7766));
                if (orderBean.orderVo.cancelStatus == 1) {
                    llAgree.setVisibility(View.VISIBLE);
                } else {
                    llAgree.setVisibility(View.GONE);
                }
                tvTime.setTextColor(getResources().getColor(R.color.color_FFFC807B));
                tvTime.setVisibility(View.VISIBLE);
                interval((int) DateUtil.getunPayCountdown(orderBean.orderVo.currentTime, orderBean.orderVo.createTime,orderBean.orderVo.buyNoPayTimeOut, DateUtil.YY_MM_DD_HH_MM_SS));
                break;
            case BUY_PAYED:
                llAgree.setVisibility(View.GONE);
                vBottomLine.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvPayState.setText(getResources().getString(R.string.order_pay));
                btRight1.setVisibility(View.GONE);
                llAgree.setVisibility(View.GONE);
                tvTime.setTextColor(getResources().getColor(R.color.color_FF5AC792));
                tvTime.setVisibility(View.VISIBLE);
                interval((int) DateUtil.getPayedCountdown(orderBean.orderVo.currentTime, orderBean.orderVo.createTime, DateUtil.YY_MM_DD_HH_MM_SS));
                break;
            case BUY_REPRESENTATION:
                tvTime.setVisibility(View.GONE);
                llAgree.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                vBottomLine.setVisibility(View.VISIBLE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FFFF7766));
                tvPayState.setText(getResources().getString(R.string.the_orther_appeal));
                //联系平台
                btRight1.setVisibility(View.VISIBLE);
                btRight1.setText(getString(R.string.contact_platform));
                btRight1.setTextColor(getResources().getColor(R.color.color_FF516168));
                btRight1.setBackgroundColor(getResources().getColor(R.color.colorWhite));
                break;
            case BUY_CANCLED:
                tbCancled.setVisibility(View.VISIBLE);
                llAgree.setVisibility(View.GONE);
                tvPayState.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                tvPayState.setText(getResources().getString(R.string.order_cancle));
                llPayInfom.setVisibility(View.GONE);
                llBottom.setVisibility(View.GONE);
                tvTime.setVisibility(View.GONE);
                break;
            case BUY_FINISHED:
                $setResult();
                refreshOrder();
                Bundle bundle = new Bundle();
                bundle.putSerializable(AllOrderFragment.ORDER_ID, orderBean.orderVo.id);
                bundle.putBoolean(OrderFinishedActivity.ISNORMALORDER, false);
                $startActivity(OrderFinishedActivity.class, bundle, true);
                break;
        }
    }

    /**
     * 获取融云未读消息数
     */
    private void getRongUnreadCount() {
        RongIMClient.getInstance().getUnreadCount(Conversation.ConversationType.PRIVATE, orderBean.buyVo.id, new RongIMClient.ResultCallback<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                if (integer != null && integer > 0) {
                    tvRed.setVisibility(View.VISIBLE);
                    tvRed.setText(String.valueOf(integer));
                } else {
                    tvRed.setVisibility(View.GONE);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
            }
        });
    }

    /**
     * 未付款和已付款倒计时款操作
     */
    public void interval(int count) {
        CountDownUtils.interval(count / 1000, new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposable = d;
            }

            @Override
            public void onNext(Long along) {
                tvTime.setText(DateUtil.getTimeMinutesSecond(along));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //当倒计时完成，则需要请求订单详情接口，刷新数据，取消订单
                mPresenter.doLoadData(orderId);
            }
        });
    }

    @Override
    protected void initPermissions() {
        super.initPermissions();
    }

    @OnClick({R.id.rl_contact, R.id.bt_call, R.id.bt_right1, R.id.bt_agree, R.id.bt_refuse, R.id.back_tv})
    public void onCliekEvent(View view) {
        switch (view.getId()) {
            case R.id.rl_contact: //联系对方
                isRefreshRedMess = true;
                RongIM.getInstance().startConversation(this, Conversation.ConversationType.PRIVATE, orderBean.buyVo.id, orderBean.buyVo.nickName);
                break;
            case R.id.bt_call://打电话
                call();
                break;
            case R.id.back_tv:
                refreshOrder();
                finish();
                break;
            case R.id.bt_right1:// z最右边的按钮
                btRight1Click();
                break;
            case R.id.bt_agree:// 同意对方取消交易
                mPresenter.confirmCancel(orderBean.orderVo.id);
                break;
            case R.id.bt_refuse:// 拒绝对方取消交易
                mPresenter.rejectCancle(orderBean.orderVo.id);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isRefreshRedMess) {
            getRongUnreadCount();
            isRefreshRedMess = false;
        }
    }

    private void btRight1Click() {
        switch ((orderBean.orderVo.status)) {
            case BUY_UNPAID://未付款 ：我已付款  按钮
                payingClick();
                break;
            case BUY_REPRESENTATION://申诉中---没有状态
                contractService();
                break;
        }
    }

    private void copyData(String bankNo) {
        CommonUtil.copyData(bankNo);
        if (copyDialog == null)
            copyDialog = new SingBlocksDialog(this)
                    .setTitle(getString(R.string.copy_success))
                    .setGotText(getString(R.string.confirm), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            copyDialog.dismiss();
                        }
                    });

        copyDialog.show();
    }

    private void refreshOrder() {
        if (orderBean != null && orderBean.orderVo != null && statue != orderBean.orderVo.status)//订单状态发生改变时 通知更新红点
        {
            postSticky(new Event.RefreshOrderListEvent(orderBean.orderVo.status, false));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SALE_PAYED_REQUEST) {
            setResult(RESULT_OK);
            refreshLayout.autoRefresh(0, 10, 1);
        }
    }

    private void call() {
        if (callDailog == null) {
            callDailog = new MultipleBlocksDialog(this)
                    .setContent(orderBean.buyVo.phone)
                    .setTitle(orderBean.buyVo.nickName)
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.dial), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CommonUtil.callPhone(AdBuyOrderDetailActivity.this, orderBean.buyVo.phone);
                            callDailog.dismiss();
                        }
                    });
        }
        callDailog.show();
    }


    /**
     * 我已付款操作----点击我已付款，然后需要对方确认收款，这边才能操作
     */
    private void payingClick() {
        if (payingDailog == null)
            payingDailog = new MultipleBlocksDialog(this)
                    .setContent(getString(R.string.confirm_paying_hint))
                    .setTitle(getString(R.string.confirm_paying))
                    .setTvCancle(getString(R.string.cancel))
                    .setTvSure(getString(R.string.confirm), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            payingDailog.dismiss();
                            mPresenter.paying(orderBean.orderVo.id);
                        }
                    });

        payingDailog.show();
    }

    /**
     * 联系客服
     */
    private void contractService() {
        requestPermission(new OnPermissionsResult() {
            @Override
            public void onAllow(List<String> allowPermissions) {
                goCustomService();
            }

            @Override
            public void onNoAllow(List<String> noAllowPermissions) {
                BlocksToast.get().showToast(getResources().getString(R.string.meiqia_error));
            }

            @Override
            public void onForbid(List<String> noForbidPermissions) {
                BlocksToast.get().showToast(getResources().getString(R.string.meiqia_error));
            }

            @Override
            public void onLowVersion() {
                goCustomService();
            }
        }, SaleOrderDetailActivity.EXTERNAL_PERMISSION);

    }

    private void goCustomService() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (callDailog != null)
            callDailog.onDestroy();
        callDailog = null;

        if (payingDailog != null)
            payingDailog.onDestroy();
        payingDailog = null;

        if (mDisposable != null && !mDisposable.isDisposed())
            mDisposable.dispose();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        refreshOrder();
    }
}
